<template>
  <div class="chat-container">
    <div class="chat-messages" ref="chatBox">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        class="message"
        :class="message.sender === 'user' ? 'user-message' : 'ai-message'"
      >
        <!-- AI消息保持头像在左侧 -->
        <div v-if="message.sender === 'ai'" class="avatar">
          <i class="fa-solid fa-robot"></i>
          <img style="height: 45px; width: 45px; border-radius: 22px;" 
          src="/ai.png"/>
        </div>
        
        <div class="message-content">
          <div v-if="message.sender === 'user'" class="message-text">
            {{ message.content }}
          </div>
          <div v-else class="message-text" v-html="message.htmlContent || ''"></div>
        </div>
        
        <!-- 用户消息头像放在右侧 -->
        <div v-if="message.sender === 'user'" class="avatar">
          <i class="fa-solid fa-user"></i>
          <img style="height: 45px; width: 45px; border-radius: 22px;" 
          src="https://happy-recycling-station.oss-cn-beijing.aliyuncs.com/happy-recycling-station.png" />
        </div>
      </div>

      <div v-if="isLoading" class="loading-indicator">
        <div class="spinner"></div>
        <p>AI正在思考...</p>
      </div>
    </div>

    <div class="chat-input">
      <textarea
        v-model="userInput"
        placeholder="请输入您的问题..."
        @keyup.enter="sendMessage"
        :disabled="isLoading"
      ></textarea>
      <button @click="sendMessage" :disabled="isLoading">
        <i class="fa-solid fa-paper-plane"></i> 发送
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import MarkdownIt from 'markdown-it';

// 初始化 markdown-it 实例
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
});

// 聊天数据
const messages = ref([]);
const userInput = ref('');
const isLoading = ref(false);
const chatBox = ref(null);
let controller = null; // 控制中断请求

// 页面加载时添加欢迎语
onMounted(() => {
  messages.value.push({
    sender: 'ai',
    content: '您好！我是灵职校盟AI求职助手，有什么可以帮您的吗？',
    htmlContent: md.render('您好！我是灵职校盟AI求职助手，有什么可以帮您的吗？')
  });

  nextTick(() => {
    scrollToBottom();
  });
});

// 发送消息
async function sendMessage() {
  const content = userInput.value.trim();
  if (!content || isLoading.value) return;

  // 添加用户消息
  messages.value.push({
    sender: 'user',
    content: content
  });

  userInput.value = '';
  isLoading.value = true;

  // 创建AI回复占位符
  const aiMessage = {
    sender: 'ai',
    content: '',
    htmlContent: ''
  };
  messages.value.push(aiMessage);

  await nextTick();
  scrollToBottom();

  try {
    controller = new AbortController();
    const token = JSON.parse(localStorage.getItem('jobseekerInfo'))?.token || '';

    const response = await fetch(`/api/jobSeeker/chats?content=${encodeURIComponent(content)}`, {
      signal: controller.signal,
      headers: {
        'jobSeekerToken': token
      }
    });

    if (!response.body) throw Error('不支持流式传输');
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      aiMessage.content += chunk;
      aiMessage.htmlContent = md.render(aiMessage.content); // 增量更新HTML

      messages.value = [...messages.value]; // 触发响应式更新
      scrollToBottom();
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('请求失败:', error.message);
      aiMessage.htmlContent = `<span style="color:red;">【错误】${error.message}</span>`;
      messages.value = [...messages.value];
    }
  } finally {
    isLoading.value = false;
    controller = null;
  }
}

// 停止生成（可选）
function stopGenerate() {
  if (controller) {
    controller.abort();
    isLoading.value = false;
  }
}

// 自动滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (chatBox.value) {
      chatBox.value.scrollTop = chatBox.value.scrollHeight + 1000;
    }
  });
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  width: 800px;
  height: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 8px;
  background-color: #f5f5f5;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.message {
  display: flex;
  margin-bottom: 15px;
  animation: fadeIn 0.3s ease-in-out;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #0d6efd;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  margin-left: 10px;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 20px;
  position: relative;
}

.user-message .message-content {
  background-color: #0d6efd;
  color: white;
}

.ai-message .message-content {
  background-color: #e5e5ea;
  color: #333;
}

.message-text {
  word-wrap: break-word;
  line-height: 1.5;
}

.chat-input {
  display: flex;
  gap: 10px;
}

textarea {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 20px;
  resize: none;
  outline: none;
  transition: border-color 0.3s;
}

textarea:focus {
  border-color: #0d6efd;
}

button {
  padding: 10px 20px;
  background-color: #0d6efd;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

button:hover {
  background-color: #0b5ed7;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.loading-indicator {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 10px;
  justify-content: center;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 3px solid #f3f3f3;
  border-radius: 50%;
  border-top: 3px solid #0d6efd;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>